<?php
if (!isset($_COOKIE['user_id'])) {
    header("Location: ../main/login.php");
    exit();
}

$user_id = $_COOKIE['user_id'];

include('../resource/db/db.php');

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $username = $_POST['username'];
    $email = $_POST['email'];
    $password = isset($_POST['password']) ? $_POST['password'] : null;
    $confirm_password = isset($_POST['confirm_password']) ? $_POST['confirm_password'] : null;
    $avatar = $_FILES['avatar'];

    // 验证输入
    if (empty($username) || empty($email)) {
        echo "用户名和邮箱不能为空。";
        exit();
    }

    if ($password && $password !== $confirm_password) {
        echo "两次输入的密码不一致。";
        exit();
    }

    $update_query = "UPDATE users SET username='$username', email='$email'";

    if ($password) {
        $hashed_password = password_hash($password, PASSWORD_DEFAULT);
        $update_query .= ", password='$hashed_password'";
    }

    // 处理头像上传
    if ($avatar['error'] == UPLOAD_ERR_OK) {
        $upload_dir = '../uploads/avatars/';
        $avatar_name = $user_id . '_' . basename($avatar['name']);
        $upload_file = $upload_dir . $avatar_name;

        if (move_uploaded_file($avatar['tmp_name'], $upload_file)) {
            $update_query .= ", avatar='$avatar_name'";
        } else {
            echo "头像上传失败。";
            exit();
        }
    }

    $update_query .= " WHERE user_id='$user_id'";

    if ($conn->query($update_query) === TRUE) {
        header("Location: center.php");
    } else {
        echo "更新失败: " . $conn->error;
    }
} else {
    header("Location: center.php");
}
?>
